(function (window) {

    window.wCheck = function (data, type) {
        var success = false, error = "";
        if (!data || data == "") {
            return {"success": success, "error": "请输入信息"};
        }
        if (!type) {
            return {"success": success, "error": "数据校验出错"};
        }
        switch (type) {
            //校验文本长度
            case 'text':
                if (data.length > 50) { //默认不超过100字符
                    error = '请保持50字以内';
                }
                break;
            case 'bank':
                if(!/^(\d{16}|\d{19})$/.test(data)){
                    error = '银行卡号格式不正确'
                }
                break;
            case 'idCard':
                if(!/^[1-9]([0-9]{14}|([0-9]{17}|[0-9]{16}X|[0-9]{16}x))$/.test(data)){
                    error = '身份证格式不正确'
                }
                break;
            case 'cvv2':
                if(!/^[0-9]{3}$/.test(data)){
                    error = 'CVV码为3位数字'
                }
                break;
            case 'dateNum':
                if(!/^((0[1-9])|(1[0-2]))[0-9]{2}$/.test(data)){
                    error = '有效期格式:月年(如:1220)'
                }
                break;
            // 邮箱校验
            case 'email':
                if (!/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i.test(data)) {
                    error = "邮箱格式错误";
                }
                break;
            // 手机号校验
            case 'mobilePhone':
                if (!/^[1]{1}[3456789]{1}[0-9]{9}$/g.test(data)) {
                    error = "手机号码格式错误";
                }
                break;
            //投保城市校验
            case 'InsureArea':
                if (data.indexOf("巢湖市") >= 0) {
                    error = "城市机构不存在";
                } else if (data.indexOf("请选择投保地区") > 0) {
                    error = "请选择投保地区"
                }
                break;
            //车牌号码校验
            case 'carNo':
                if (data.length == 7 && /^[\u4e00-\u9fa5][a-zA-Z][a-zA-Z0-9]*$/.test(data)) {

                } else if (data.length == 3 && /^[\u4e00-\u9fa5][a-zA-Z]/.test(data) && data.substring(2, 3) == "*") {

                } else {
                    error = "请参照“粤ABC123”格式填写车牌号";
                }
                break;
            /*车辆座位数*/
            case 'seats':
                if (parseInt(data) < 5 || parseInt(data) > 9) {
                    error = "车辆座位数请填写5~9任一数字";
                }
                break;
            case 'username':
                if(!/^(([\u4E00-\u9FA5]{2,10}(?:·[\u4E00-\u9FA5]{2,10})*)|([a-zA-Z]{2,20}))$/.test(data)){
                    error = "姓名格式错误，请重新输入";
                }
            //车主姓名
            case 'name':
                var totalLength = data.length;
                var cnArray = data.match(/[\u4e00-\u9fa5]/g);
                if (cnArray) {
                    totalLength += cnArray.length;
                }
                for (var i = 0; i < data.length; i++) {
                    if (data.charCodeAt(i) == 183) {
                        if (i == 0 || i == data.length - 1) {
                            error = "姓名错误，请重新输入";
                        }
                        if (data.charCodeAt(i + 1) == 183) {
                            error = "姓名错误，请重新输入";
                        }
                    }
                }
                var filterArr = ['公司', '有限', '集团', '股份', '大学'], filterLen = filterArr.length;
                while (filterLen--) {
                    if (data.indexOf(filterArr[filterLen]) > -1) {
                        error = "抱歉，不支持企业用车投保";
                    }
                }
                var filterArr2 = ['不详', '不祥', '不知道', '未知'], filterLen2 = filterArr2.length;
                while (filterLen2--) {
                    if (data.indexOf(filterArr2[filterLen2]) > -1) {
                        error = "姓名错误，请重新输入";
                    }
                }
                if (totalLength > 30 || totalLength < 4) {
                    error = "姓名错误，请重新输入";
                }
                var nameReg = /^(([\u4e00-\u9fa5a-zA-Z·]*[\u4e00-\u9fa5]+[\u4e00-\u9fa5a-zA-Z·]*)|([a-zA-Z\s]+))$/;
                if (!nameReg.test(data)) {//字符逐个判断
                    error = "姓名错误，请重新输入";
                }
                break;
            /*车架号*/
            case "frameNo":
                if (!/^[\u4e00-\u9fa5]?[a-zA-Z0-9\*]{17}$/.test(data)) {
                    error = '车架号错误，请重新输入';
                } else if (/[qQ]/.test(data)) {
                    error = '车架号不能含O﹑I﹑Q，请重新输入';
                } else if (/[oOiI]/.test(data)) {
                    error = '车架号不能含O﹑I﹑Q，请重新输入';
                }
                break;
            /*发动机*/
            case "engineNo":
                if (!/^[\u4e00-\u9fa5]?[a-zA-Z0-9\*]{4,21}$/.test(data)) {
                    error = '请正确填写发动机号！';
                }
                break;
            /*发票号*/
            case "vehicleCertiNo":
                if (!(v == '' || /^[0-9a-zA-Z]{4,50}$/.test(data))) {
                    error = "发票号填写不正确";
                }
                break;

        }
        error == "" && (success = true); //如果没有错误信息，则正确
        return {"success": success, "error": error};
    };
    window.limitName = function(obj,lengths) {
        var str = obj.val();
        var sum = 0 ;
        var count = 0;
        var reg = new RegExp("[\u4E00-\u9FA5]");
        for (var i=0; i<str.length; i++) {
            if (reg.test(str.charAt(i))) {
                sum += 2;
            } else {
                sum ++;
            }
            if(sum > lengths){
                obj.attr('maxlength',count);
            }else{
                count++;
            }
        }
    }
    window.limitLength = function(obj,lengths) {
        var str = obj.val();
        var sum = 0 ;
        var count = 0;
        var reg = new RegExp("[\u4E00-\u9FA5]");
        for (var i=0; i<str.length; i++) {
            if (reg.test(str.charAt(i))) {
                sum += 2;
            } else {
                sum ++;
            }
            if(sum > lengths){
                str = str.substring(0, count);
            }else{
                count++;
            }
        }
        obj.val(str);
    }

    window.wUppercase = function (str) {
        return str.replace(/[a-z]/g, function (ch) {
            return String.fromCharCode(ch.charCodeAt(0) & ~32);
        });
    }
    window.wfuc = {
        /**
         * 自动删除空格转换为大写，移除焦点触发
         * @param {object} el
         */
        autoDeleteCharsToUpperCase: function (el) {
            var pThis = this;
            el.on('keyup', function () {
                var self = $(this), str = pThis.deleteChars(self.val(), [/\s/g]);
            });
            el.on('blur', function () {
                var self = $(this), value = self.val().toUpperCase();
                self.val(value);
            });
        },
        /**
         * 自动删除字符串中符合匹配内容的字符
         * @param {String} str
         * @param {Array} chars
         */
        deleteChars: function (str, chars) {
            var result = '', s = '', c = '', r = false, clen = chars.length, n = true;

            if (!_.isArray(chars)) {
                chars = [chars];
            }

            for (var i = 0, len = str.length; i < len; i++) {
                s = str[i];
                n = true;

                for (var j = 0; j < clen; j++) {
                    c = chars[j];

                    if (_.isRegExp(c)) {
                        if (c.test(s)) {
                            n = false;
                            break;
                        }
                    } else if (s == c) {
                        n = false;
                        break;
                    }
                }

                if (n) {
                    result += s;
                }
            }

            return result;
        },

        /**
         * 将元素中的文字自动转换为大写形式, 并删除空白字符
         * @param {object} el
         */
        autoToLocaleUpperCase: function (el) {
            el.on('keyup', function (e) {
                var self = $(this), val = self.val(), e = window.event || e;
                if (val) {
                    val = val.replace(/\s/g, '');
                    self.val(val.toLocaleUpperCase());
                }
            })
        },

        /**
         * 转换日期格式
         * @param {object} el
         */
        toFMD: function (date) {
            var month = date.getMonth();
            if (month == 1) {
                month = "0" + 1;
            } else if (month < 9) {
                month = "0" + (month + 1);
            } else {
                ++month;
            }
            var day = date.getDate() > 9 ? date.getDate() : ("0" + date.getDate());
            return date.getFullYear() + "-" + month + "-" + day;
        },

        /**
         * 格式化价格-》万元
         * @param {int} price
         * */
        priceFormat: function (price) {
            if (!price) return;
            var priceStr = price.toString();
            if (priceStr.lastIndexOf(".") != -1) {
                priceStr = priceStr.substr(0, priceStr.lastIndexOf("."));
            }
            var priceF;
            if (priceStr.length > 4) {
                priceF = priceStr.substring(0, (priceStr.length - 4));
                priceF += (priceStr.slice(-4, -3) !== '0') ? "." + priceStr.slice(-4, -3) : '';
                priceF += "万";
            } else {
                priceF = priceStr + "元";
            }
            return priceF;
        },
        priceFormat2: function (price) {
            if (!price) return;
            var priceStr = price.toString();
            if (priceStr.lastIndexOf(".") != -1) {
                priceStr = priceStr.substr(0, priceStr.lastIndexOf("."));
            }
            return priceStr + "元";
        },
        /**
         * wfuc.floatToFixed("299",2)=>299.00
         * @param num
         * @param point 保留小数点后多少位
         */
        floatToFixed: function (num, point) {
            if (!num) return num;
            return parseFloat(num).toFixed(parseInt(point));
        },
        /**
         * 调用comboSave接口的统一处理，判断是否提示错误或者跳转页面
         * 可能跳转到：交强险、商业险、确认车型
         * @param json Ajax返回的数据
         * 例如：
         * wAjax("comboSavaInfo", ckData, function (json) {
                    wfuc.comboSaveJump(json);
                }, null)
         */
        comboSaveJump: function (json) {
            var data = JSON.parse(json);
            if (data.error) {
                wTips(data['error']['value']);
            }
            /* resultCode:
             *1:进入交强险页面；
             *2:进入商业险页面；
             *11:拒保；
             *12: 平台投保查询返回多个车型,需要确认平台车型，进入确认车型页；
             *560: 投保流程超时；*/

            wData['flowid'] = data['flowid'];
            /*默认时间可投保时间段为：90天*/
            wData["TCI"]['canAdvanceDays'] = "90";
            wData["VCI"]['canAdvanceDays'] = "90";
            /* 续保默认false */
            wData['renewal'] = false;
            if (data['inputs']) {
                $.each(data['inputs'], function (k, v) {
                    if (v["name"] === "forceQuote.beginDate") {
                        wData['TCI']['forceQuoteBeginDate'] = v['value'];
                    }
                    if (v["name"] === "bizQuote.beginDate") {
                        wData['VCI']['bizQuoteBeginDate'] = v['value'];
                    }
                })
            }
            /*交强险*/
            if (data.hasOwnProperty('forceQuoteResult')) {
                wData['TCI']['forcePremium'] = data['forceQuoteResult']['forcePremium'];
                wData['TCI']['taxPremium'] = data['forceQuoteResult']['taxPremium'];
                wData['TCI']['tax'] = data['forceQuoteResult']['tax'];
                wData["TCI"]['canAdvanceDays'] = data['forceQuoteResult']['canAdvanceDays'];
                wData["applyTCI"] = true;
            }
            /*商业险*/
            var circVehicleResultCode;
            if (data.hasOwnProperty('bizQuoteConfig')) {
                /*判断是否续保*/
                if (data['bizQuoteConfig'].hasOwnProperty('renewal')) {
                    wData['renewal'] = true;
                }
                wData["VCI"]['canAdvanceDays'] = data['bizQuoteConfig']['canAdvanceDays'];
                wData['VCI']['passengerSeats'] = data['bizQuoteConfig']['passengerSeats'];
                wData['VCI']['amount01Default'] = data['bizQuoteConfig']['amount01Default'];
                wData['VCICustom']['amount01Default'] = data['bizQuoteConfig']['amount01Default'];
                circVehicleResultCode = data["bizQuoteConfig"]["circVehicleResultCode"];
            }

            if (data['resultCode'] === "11") {
                wTips("您的车辆暂时不能投保");
            }
            else if (data['resultCode'] === "560") {
                wTips("投保流程超时，请重新提交");
            }
            else if (data['resultCode'] === "1" || data['resultCode'] === "2" || data['resultCode'] === "3") {

                if (circVehicleResultCode === '1') {
                    wTips("车型库无对应车型,请确认车架号、发动机号是否填写正确！");
                    return;
                }
                /*wData["insuranceStatus"]
                 * 用于标识以下三种情况。
                 * 1.单包交强险
                 * 2.单包商业险
                 * 3.2者均保。
                 * string 类型
                 * */

                wData["insuranceStatus"] = data['resultCode'];

                if (data['resultCode'] === "1") {
                    /*跳转到交强险
                     * 单保交强险
                     * */
                    location.hash = "TCI";
                } else if (data['resultCode'] === "2") {
                    /*单保商业险*/
                    wData["applyTCI"] = false;
                    location.hash = "VCI";
                } else {
                    /*商交都保*/
                    location.hash = "TCI";
                }

            }
            else if (data['resultCode'] === "12") {
                /*跳转到确认车型*/
                var modelList = data['models'];
                var renderData = [];
                $.each(modelList, function (k, v) {
                    renderData.push({standard_name: v["modelName"], description: v["description"], modelCode: v["modelCode"], marketDate: v["marketDate"], price: v["price"]});
                });
                wData.confirmCarType.renderData = renderData;
                wData.confirmCarType.renderOnly = true;
                location.hash = "confirmCarType";
            }
            else if (data['resultCode'] == "1038") {
                var promptText = data['forceQuoteResult']['promptText'];
                wTips(promptText);

            }
            else if (data['resultCode'] == "9200") {
                var text = data['forceQuoteResult']['promptText'];
                wData["insuranceStatus"] = "1";
                wAlert(text, function () {
                    location.hash = "TCI";
                }, null);
            }
            else if (data['resultCode'] == "9300") {
                wData["insuranceStatus"] = "2";
                var textx = data['forceQuoteResult']['promptText'];
                wAlert(textx, function () {
                    wData["applyTCI"] = false;
                    location.hash = "VCI";
                }, null);
            } else if (data['resultCode'] === "1039") {
                /*单商业险投保，投保查询异常提示信息*/
                wAlert(data['tomodelconfirm']['errorMsg'], null);
            }
            else {
                wTips("后端服务出错");
            }
        },
        /**
         * 校验地址
         * @param k
         */
        checkAddress: function (objValue) {
            var mes = [true, '地址不能为空', '地址不符合规范,请正确填写', '地址不能少于6个汉字或12个字母'];
            var addressegi = /^[a-zA-Z\u4e00-\u9fa50-9\-\#\,]*[a-zA-Z\u4e00-\u9fa5]+[a-zA-Z\u4e00-\u9fa50-9\-\#\,]*$/;
            //地址不能为全数字
            objValue = $.trim(objValue.toUpperCase());
            //改成大写
            // objValue = objValue.replace(/\s+/g, ''); //stz 前台验证不让后台出现错误提示以出现正则表达式的错误提示 '打算放四大 1234的'会出错
            if (objValue.replace(/\s+/g, '') == ' ') { //objValue stz
                return mes[1];
            }
            var totalLength = objValue.length;
            /*<%--中文--%>*/
            var cnArray = objValue.match(/[\u4e00-\u9fa5]/g);
            if (cnArray) {
                totalLength += cnArray.length;
            }
            if (totalLength < 12) {
                return mes[3];
            }
            if (!addressegi.test(objValue)) {
                return mes[2];
            }
            return mes[0];
        },
        /**
         *
         * @param num
         * @param digit
         * @returns {1234****5678}
         */
        encryptionNum: function (num, digit) {
            return num.slice(0, digit) + "****" + num.slice(-digit);
        }
    };
    window.nonNumeric = function(obj) {
        if(/[^\d]/.test(obj.val())){//替换非数字字符
            var temp_amount=obj.val().replace(/[^\d]/g,'');
            obj.val(temp_amount);
        }
    }
    window.resetWData = function () {
        var urlTempData;
        if (wData.urlData) {
            urlTempData = wData.urlData;
        }
        window.wData = {
            urlData: App.getParams(),//获取URL传参，config里面的方法
            beginHash: App.getParams("hash"),
            index: {},               //首页基本信息
            myDeal: {},
            insureBaseInfo: {},
            addVehicleInfo: {},
            confirmCarType: {},
            insurancePkg: {},                 //商业险
            insuranceCustom: {},
            confirmOrder: {},         //确认订单数据
            orderDetail: {},         //确认订单数据
            errorPage: {},         //错误页面
            additionalInfo: {}       //补充页面数据
        };
        if (urlTempData) {
            wData.urlData = urlTempData;
        }
    }
    window.wValidate = {
        /**
         * 验证证件号码
         * @param {string} c 证件 类型
         * @param {string} a 证件号码
         *01居民身份证
         *02护照
         *05驾驶证
         *06港澳回乡证或台胞证
         *03军官证
         */
        checkIdNo: function (n, c, a) {
            if (c == '')
                return '请选择' + n + '证件类型';
            if (a == "") {
                return "请填写" + n + "证件号码";
            }
            var b = "证件号码不符合规范，请正确填写.";
            if (c == "01" && this.checkIdCard(n, a) != true) {
                return this.checkIdCard(n, a);
                //身份证
            } else if (c == '06' && this.validateGangao(a) != true) {
                return '港澳回乡证或台胞证不正确,请您重新检查。';
                //港澳回乡证或台胞证
            } else if (c == "02" && !this.byteLength(a, 3, 18)) {
                return b;
                //护照,允许中文字符
            } else if (c == '03' && !this.byteLength(a, 6, 20)) {
                return b;
                //军官证,允许中文字符，6，20
            } else if (c == '05' && !this.license(a)) {
                return b;
                //驾照，英文数字
            } else {
                if ((c == "2" || c == "3") && !this.byteLength(a, 6, 20)) {
                    return b;
                } else {
                    if ((c == "4" || c == "18") && !this.byteLength(a, 5, 20)) {
                        return b;
                    } else {
                        if (!this.byteLength(a, 1, 30)) {
                            return b;
                        }
                    }
                }

            }
            return true;
        },
        license: function (a) {
            if (!this.byteLength(a, 5, 20))
                return false;
            else if (!/^[a-zA-Z\d]*$/.test(a))
                return false;
            else
                return true;

        },
        /**
         * 获取字符串真正长度,并检测合法性
         * @param  {string} e 证件号
         * @param  {string} d 最小长度
         * @param  {string} c 最大长度
         */
        byteLength: function (e, d, c) {
            if (e == null) {
                return false;
            }
            var a = e.length;
            var b = 0;
            for (i = 0; i < a; i++) {
                if ((e.charCodeAt(i) & 65280) != 0) {
                    b++;
                }
                b++;
            }
            if (b > c || b < d) {
                return false;
            }
            return true;
        },
        /**
         * 验证身份证号码
         * param {string} k
         */
        checkIdCard: function (n, k) {
            var pa = {};
            k = k.toUpperCase();
            var m = [true, "您输入的" + n + "身份证号码位数不对!", "您输入的" + n + "身份证号码错误", "您输入的" + n + "身份证号码错误", "您输入的" + n + "身份证号码错误", "您输入的" + n + "身份证号码错误"];
            var c = {
                11: "\u5317\u4eac",
                12: "\u5929\u6d25",
                13: "\u6cb3\u5317",
                14: "\u5c71\u897f",
                15: "\u5185\u8499\u53e4",
                21: "\u8fbd\u5b81",
                22: "\u5409\u6797",
                23: "\u9ed1\u9f99\u6c5f",
                31: "\u4e0a\u6d77",
                32: "\u6c5f\u82cf",
                33: "\u6d59\u6c5f",
                34: "\u5b89\u5fbd",
                35: "\u798f\u5efa",
                36: "\u6c5f\u897f",
                37: "\u5c71\u4e1c",
                41: "\u6cb3\u5357",
                42: "\u6e56\u5317",
                43: "\u6e56\u5357",
                44: "\u5e7f\u4e1c",
                45: "\u5e7f\u897f",
                46: "\u6d77\u5357",
                50: "\u91cd\u5e86",
                51: "\u56db\u5ddd",
                52: "\u8d35\u5dde",
                53: "\u4e91\u5357",
                54: "\u897f\u85cf",
                61: "\u9655\u897f",
                62: "\u7518\u8083",
                63: "\u9752\u6d77",
                64: "\u5b81\u590f",
                65: "\u65b0\u7586",
                71: "\u53f0\u6e7e",
                81: "\u9999\u6e2f",
                82: "\u6fb3\u95e8",
                91: "\u56fd\u5916"
            };
            var b, l;
            var e, j;
            var a = new Array();
            a = k.split("");
            if (k == "") {
                return true;
            }
            if (c[parseInt(k.substr(0, 2))] == null) {
                return m[4];
            }
            switch (k.length) {
                case 15:
                    if ((parseInt(k.substr(6, 2)) + 1900) % 4 == 0 || ((parseInt(k.substr(6, 2)) + 1900) % 100 == 0 && (parseInt(k.substr(6, 2)) + 1900) % 4 == 0)) {
                        ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$/;
                    } else {
                        ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$/;
                    }
                    if (ereg.test(k)) {
                        var o = k.substr(6, 2);
                        var f = k.substr(8, 2);
                        var n = k.substr(10, 2);
                        if (pa && pa.oServerDate) {
                            var g = pa.oServerDate;
                        } else {
                            var h = new Date();
                            var g = new Date(h.getFullYear(), h.getMonth(), h.getDate());
                        }
                        var d = new Date(o, parseInt(f, 10) - 1, n);
                        if ((Date.parse(d) - Date.parse(g)) >= 0) {
                            return m[5];
                        }
                        return m[0];
                    } else {
                        return m[2];
                    }
                    break;
                case 18:
                    if (parseInt(k.substr(6, 4)) % 4 == 0 || (parseInt(k.substr(6, 4)) % 100 == 0 && parseInt(k.substr(6, 4)) % 4 == 0)) {
                        ereg = /^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$/;
                    } else {
                        ereg = /^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$/;
                    }
                    if (ereg.test(k)) {
                        e = (parseInt(a[0]) + parseInt(a[10])) * 7 + (parseInt(a[1]) + parseInt(a[11])) * 9 + (parseInt(a[2]) + parseInt(a[12])) * 10 + (parseInt(a[3]) + parseInt(a[13])) * 5 + (parseInt(a[4]) + parseInt(a[14])) * 8 + (parseInt(a[5]) + parseInt(a[15])) * 4 + (parseInt(a[6]) + parseInt(a[16])) * 2 + parseInt(a[7]) * 1 + parseInt(a[8]) * 6 + parseInt(a[9]) * 3;
                        b = e % 11;
                        j = "F";
                        l = "10X98765432";
                        j = l.substr(b, 1);
                        if (j == a[17]) {
                            var o = k.substr(6, 4);
                            var f = k.substr(10, 2);
                            var n = k.substr(12, 2);
                            if (pa && pa.oServerDate) {
                                var g = pa.oServerDate;
                            } else {
                                var h = new Date();
                                var g = new Date(h.getFullYear(), h.getMonth(), h.getDate());
                            }
                            var d = new Date(o, parseInt(f, 10) - 1, n);
                            if ((Date.parse(d) - Date.parse(g)) >= 0) {
                                return m[5];
                            }
                            return m[0];
                        } else {
                            return m[3];
                        }
                    } else {
                        return m[2];
                    }
                    break;
                default:
                    return m[1];
                    break;
            }
            return true;
        },
        /**
         * 验证港澳回乡证或台胞证
         */
        validateGangao: function (value) {
            value = value.toUpperCase();
            if (value.length < 8) {
                return false;
            } else if (!/^(\([a-zA-Z\d]*\)|[a-zA-Z\d])*$/.test(value)) {
                return false;
            }
            return true;
        },
        /**
         * 检测用户名
         * @param {string} name
         */
        checkName: function (name) {
            var n = name.replace(/^\s|(\s$)/, "");
            var l = n.length;
            if (n == '') {
                //return "姓名不能为空";
                return App.errorCodeText['pay020'];
            } else if (!/^([a-zA-Z]{4,50}|[\u4e00-\u9fa5]{1,25})$/.test(name)) {
                return App.errorCodeText['pay021'];
                //return '姓名只能由2位至25位中文或4位及50位英文字符构成,请正确填写';
            }
            return true;
        },
        /**
         *手机号码验证信息
         */
        checkMobil: function (number) {
            var patrn = /^1[3|4|5|8]\d{9}$/;
            number = number.trim();
            if (!patrn.test(number)) {
                return "手机号码不符合规范，请正确填写";
            }
            return true;
        },
        /**
         *  validates that the field contains a valid email address
         *
         *  @var value {mixed} - value to be checked
         *  @var paramsObj {Object} - parameters for this particular validation, see below for details
         *
         *  paramsObj properties:
         *                          failMsg {String} - the message to show when the field fails validation
         *                                                    (DEFAULT: "Must be a number!" or "Must be an integer!")
         */
        Email: function (value, paramsObj) {
            if (/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i.test(value)) {
                return true;
            }
            else {
                return false;
            }
        },
        Format: function (value, paramsObj) {
            var value = String(value);
            var paramsObj = paramsObj || {};
            var message = paramsObj.failMsg || "无效!";
            var pattern = paramsObj.pattern || /./;
            if (!pattern.test(value))
                return message;
            // negated
            return true;
        },
        /**
         * 检测发票抬头
         * @param {string} name 名称
         */
        checkInvoice: function (name) {
            var n = name.replace(/^\s|(\s$)/, "");
            if (n == '') {
                //  return "发票抬头不能为空";
                return App.errorCodeText['pay025'];
            } else if (/[a-zA-Z]{4,50}|[\u4e00-\u9fa5]{2,25}/.test(n)) {
                return true;
            } else
                return App.errorCodeText['pay026'];
            //return '发票抬头只能由2位至25位中文或4位及50位英文字符构成,请正确填写';
        },
        /**
         * 过滤非法字符
         *
         */
        filter: function (obj) {
            var result = [], c = '';
            for (var i = 0, len = obj.length; i < len; i++) {
                c = obj.charAt(i);
                switch (c) {
                    case '<':
                        result[i] = '&lt;';
                        break;
                    case '>':
                        result[i] = '&gt;';
                        break;
                    case '"':
                        result[i] = '&quot;';
                        break;
                    case '\'':
                        result[i] = '&#39;';
                        break;
                    case '%':
                        result[i] = '&#37;';
                        break;
                    case ';':
                        result[i] = '&#59;';
                        break;
                    case '(':
                        result[i] = '&#40;';
                        break;
                    case ')':
                        result[i] = '&#41;';
                        break;
                    case '&':
                        result[i] = '&amp;';
                        break;
                    case '+':
                        result[i] = '&#43;';
                        break;
                    case ' ':
                        result[i] = '&nbsp;';
                        break;
                    default:
                        result[i] = c;
                        break;
                }
            }
            return result.join('');
        }
    }


    /*
     * 下拉选择控件
     *
     */
    var wSelect = function (id) {
        return new wSelect.prototype.init(id);
    };
    wSelect.prototype = {
        init: function () {
            this.creatHtml();
            return this;
        },
        listData: {},
        creatHtml: function (date) {
            var that = this;
            var html = '<div class="opacityWrap"><div id="wSelectWrap" class="wSelectWrap"><input id="wSelectBtn" type="button"><div class="wSelect"><h4></h4><ul class="wSelect_list"></ul></div></div></div>';
            $("body").append(html);
            this.wSelect_list = $(".wSelect_list");
            this.wSelectWrap = $("#wSelectWrap");
            this.h4 = $(".wSelect h4");
            this.listMove = false; //记录选择项的滚动
            this.listStart = false;//记录选择项的触碰
            // document.onmousewheel = function(){event.preventDefault()}
            $("#wSelectWrap").on("touchmove", function (e) {
                //如果是选择项的滚动，则不拦截
                if (!that.listMove) {
                    // e.preventDefault(e);
                }
                that.listMove = false;
            });
            $("#wSelectWrap").on("touchend", function (e) {
                //如果是选择项的滚动，则不拦截
                if (!that.listStart) {
                    that.wSelectWrap.hide();
                    setTimeout(function () {
                        that.wSelectWrap.parent().hide()
                    }, 200);
                }
                that.listStart = false;
            });
            $(".wSelect_list").on("touchstart", function (e) {
                that.startClientX = e.targetTouches[0].clientX;
                that.startClientY = e.targetTouches[0].clientY;
                that.limove = false;
                that.listStart = true;
            });
            $(".wSelect_list").on("touchmove", "li", function (e) {
                that.limove = true;
                that.listMove = true; //设置选择项滚动为true
                that.listStart = false;
                that.moveClientX = e.targetTouches[0].clientX;
                that.moveClientY = e.targetTouches[0].clientY;
                that.moveType = (that.moveClientX - that.startClientX) > 0 ? "up" : "down";
                that.ulHeight = $(".wSelect_list li").length * $($(".wSelect_list li")[0]).height();
            });
            $(".wSelect_list").on("touchend", "li", function (e) {
                if (that.limove) {
                    return false;
                };
                var target = $(e.currentTarget),
                    code = target.attr("code"),
                    text = target.text();
                that.selectEl.attr("code", code);
                that.selectEl.find("input").val(text)
                that.selectEl.addClass("select");
                that.selectEl.trigger("change");
                that.selectEl.find("input").trigger("change");
                that.wSelectWrap.hide();
                App.unClick();
                setTimeout(function () {
                    that.wSelectWrap.parent().hide()
                }, 200);
            });

        },
        new: function (id) {
            var that = this;
            $.each(id, function (key, value) {
                $("body").on("tap", "#" + key, function (e) {
                    that.onfocus(e);
                });
                that.listData[key] = value;
            });
        },
        changeData: function (options) {
            var that = this;
            $.each(options, function (key, value) {
                that.listData[key] = value;
            });
        },
        onfocus: function (e) {
            if ($("#wSelectWrap").length <= 0) {
                this.creatHtml();
            }
            if ($("#wSelectWrap").css("display") != "none" || $(e.currentTarget).attr("disabled") == "disabled") {
                return;
            }
            $("#wSelectBtn").focus();
            this.selectEl = $(e.currentTarget);
            this.selectId = this.selectEl.attr("id");
            this.h4.html(this.selectEl.attr("h4"));
            this.wSelect_list.html(this.listHtml());
            this.wSelectWrap.show();
            this.wSelectWrap.parent().show();
        },
        listHtml: function () {
            var liHtml = "";
            $.each(this.listData[this.selectId], function (key, value) {
                liHtml += '<li code="' + key + '">' + value + '</li>'
            });
            return liHtml;
        },
        destroy: function () {
            /*销毁控件，解除绑定，移除html*/
            $("#wSelectWrap").off("touchmove touchend");
            $(".wSelect_list").off("touchstart touchmove touchend");
            $("body").find(".opacityWrap").remove();
        }
    }
    wSelect.prototype.init.prototype = wSelect.prototype;
    window.wSelect = wSelect();
    /*
     投保地区生成城市、地区
     */
    var wCity = function (id) {
        return new wCity.prototype.init(id);
    };

    window.cityName = [];

    wCity.prototype = {
        init: function () {
            this.creatHtml();
            return this;
        },
        creatHtml: function (date) {
            var that = this;
            var html = '<div id="wCityWrap"><div id="noSearch"></div> <div class="searchCity"><div class="placeName" id="selectCityName"></div><input type="text" id="citySearchField" placeholder="输入城市名或者拼音查询"></div><ul id="wCityUl" class="list_text list_more"></ul></div>';
            $("body").append(html);
            this.wCityWrap = $("#wCityWrap");
            this.wCityUl = $("#wCityUl");
            this.wCitySearchField = $("#citySearchField");
            router.hasHead && (this.wCityWrap.find(".searchCity").css("margin-top", "2rem"));
            //搜索城市
            //此处事件不能只用keyup因为IOS输入拼音时，选择结果，没有把它当keyup事件
            this.wCitySearchField.on("keyup", function (e) {
                var target = $(e.currentTarget),
                    cityCode = target.val().toUpperCase();
                that.inputValue = cityCode;
                if (!cityCode) {
                    that.wCityUl.html(that.provinceHtml());
                    return;
                } else {
                    that.searchCity({q: cityCode});
                }
            });
            //同时判断如果搜索框内容改变，那也进行查询
            this.wCitySearchField.on("change", function (e) {
                var target = $(e.currentTarget),
                    cityCode = target.val().toUpperCase();
                if (that.inputValue == cityCode) {
                    return;
                }
                if (!cityCode) {
                    that.wCityUl.html(that.provinceHtml());
                    return;
                } else {
                    that.searchCity({q: cityCode});
                }
            });
            this.wCityWrap.on("touchmove", function (e) {
                //如果是选择项的滚动，则不拦截
                that.listMove = false;
            });
            this.wCityUl.on("touchstart", function (e) {
                that.startClientX = e.targetTouches[0].clientX;
                that.startClientY = e.targetTouches[0].clientY;
                that.limove = false;
                that.listStart = true;
            });
            this.wCityUl.on("touchmove", "li", function (e) {
                that.limove = true;
            });
            this.wCityUl.on("touchend", "li", function (e) {
                if (that.limove) {
                    return false;
                }
                ;
                var target = $(e.currentTarget),
                    //codeType = target.attr("codeType"),
                    code = target.attr("code"),
                    carPrefix = target.attr("vehicleLicencePrefix"),
                    text = target.text();
                //隐藏搜索框跟已选中省市展示
                $("#selectCityName").text(text).show();
                that.wCitySearchField.val("").hide();
                that.searchCityMessage(code);

                /*
                 if(codeType =="provinceCode"){
                 that.selectCity({code:code});
                 that.saveObj.provinceCode = code;
                 that.saveObj.provinceName = text;
                 }else if(codeType =="cityCode"){
                 if("110100,500100,310100,120100".indexOf(code)>=0){
                 that.saveObj.provinceCode = "";
                 that.saveObj.provinceName = "";
                 }
                 that.saveObj.cityName = text;
                 that.saveObj.cityCode = code;
                 that.saveObj.carPrefix = carPrefix;
                 that.selectCity({code:code},true);
                 }else{
                 that.saveObj.areaName = text;
                 that.saveObj.areaCode = code;
                 that.saveObj.carPrefix = carPrefix;
                 back(true);
                 }
                 */
            });
        },
        selectCity: function (postData, region) {
            var that = this;
            wAjax("queryCityByProvinceCode", postData, function (data) {
                $("#citySearchField").val("");
                if (data != "[]") {
                    if (!region) {
                        that.city = typeof (data) == "string" ? JSON.parse(data) : data;
                        that.wCityUl.html(that.cityHtml(data));
                    } else {
                        that.region = typeof (data) == "string" ? JSON.parse(data) : data;
                        that.wCityUl.html(that.regionHtml(data));
                    }
                } else {
                    that.saveObj.areaName = "";
                    that.saveObj.areaCode = "";
                    back(true);
                }
            });
        },
        searchCity: function (postData) {
            var that = this;
            wAjax("citys", postData, function (data) {
                if (data.resultCode != "100") {
                    return;
                }
                that.city = data.results;
                that.wCityUl.html(that.cityHtml());
            }, null, {type: "get", data: postData});
        },
        searchCityMessage: function (cityCode) {
            var that = this;
            wAjax("cityCode", {cityCode: cityCode}, function (data) {
                if (data.resultCode != "100") {
                    return;
                }
                if (data.childCitys && data.childCitys.length > 0) {
                    that.saveObj.cityName = data.cityName;
                    that.saveObj.cityCode = data.cityCode;
                    that.city = data.childCitys;
                    that.wCityUl.html(that.cityHtml());
                } else if (data.cityInfo) {
                    that.saveObj.cityName = data.cityInfo.cityName;
                    that.saveObj.cityCode = data.cityInfo.cityCode;
                    that.saveObj.carPrefix = data.cityInfo.carPrefix;
                    back(true);
                }
            }, null, {type: "get"});
        },
        new: function (id, obj) {
            var that = this;
            that.saveObj = obj;
            $("#" + id).on("touchend", function (e) {
                that.onfocus(e);
            });
        },
        onfocus: function (e) {
            if ($("#wCityWrap").length <= 0) {
                this.creatHtml();
            }
            $("#noSearch").show();
            setTimeout(function () {
                $("#noSearch").hide()
            }, 500);
            var target = $(e.currentTarget).find("p");
            var dataType = target.attr("dataType");
            if (dataType == "area") {
                var cityCode = target.attr("cityCode"),
                    cityName = target.attr("cityName");
                $("#selectCityName").text(cityName).show();
                this.wCitySearchField.val("").hide();
                this.selectCity({code: cityCode}, true);
            } else {
                this.wCityUl.html(this.provinceHtml());
                $("#selectCityName").text("").hide();
                this.wCitySearchField.show();
            }
            this.wCityWrap.show();
        },
//        省不用调用接口
        province: [
            {"cityCode": "110000", "vehicleLicencePrefix": "京A", "cityName": "北京市"},
            {"cityCode": "120000", "vehicleLicencePrefix": "津A", "cityName": "天津市"},
            {"provinceName": "福建省", "provinceCode": "350000"},
            {"provinceName": "辽宁省", "provinceCode": "210000"},
            {"provinceName": "四川省", "provinceCode": "510000"},
            {"provinceName": "江苏省", "provinceCode": "320000"},
            {"provinceName": "浙江省", "provinceCode": "330000"},
            {"provinceName": "广东省", "provinceCode": "440000"}

            /*
             {"provinceName":"安徽省","provinceCode":"340000"},
             {"provinceName":"广东省","provinceCode":"440000"},
             {"provinceName":"河北省","provinceCode":"130000"},
             {"provinceName":"河南省","provinceCode":"410000"},
             {"provinceName":"湖北省","provinceCode":"420000"},
             {"provinceName":"湖南省","provinceCode":"430000"},
             {"provinceName":"江西省","provinceCode":"360000"},
             {"provinceName":"山东省","provinceCode":"370000"},
             {"provinceName":"山西省","provinceCode":"140000"},
             {"provinceName":"内蒙古自治区","provinceCode":"150000"},
             {"provinceName":"陕西省","provinceCode":"610000"},
             {"provinceName":"新疆维吾尔自治区","provinceCode":"650000"},
             {"provinceName":"云南省","provinceCode":"530000"}*/
        ],
        provinceHtml: function (listData) {
            var liHtml = "";
            $.each(this.province, function (key, value) {
                liHtml += '<li codeType="' + (value.provinceCode == undefined ? "cityCode" : "provinceCode")
                    + '" code="' + (value.provinceCode == undefined ? value.cityCode : value.provinceCode)
                    + '" vehicleLicencePrefix="' + (value.vehicleLicencePrefix == undefined ? "" : value.vehicleLicencePrefix)
                    + '">' + (value.provinceName == undefined ? value.cityName : value.provinceName)
                    + '</li>'
            });
            return liHtml;
        },
        cityHtml: function (listData) {
            var liHtml = "";
            $.each(this.city, function (key, value) {
                liHtml += '<li codeType="cityCode" code="' + value.cityCode + '" vehicleLicencePrefix="' + value.vehicleLicencePrefix + '">' + value.cityName + '</li>'
            });
            return liHtml;
        },
        regionHtml: function (listData) {
            var liHtml = "";
            $.each(this.region, function (key, value) {
                liHtml += '<li codeType="areaCode" code="' + value.cityCode + '" vehicleLicencePrefix="' + value.vehicleLicencePrefix + '">' + value.cityName + '</li>'
            });
            return liHtml;
        },
        newDate: function () {
        }
    };
    wCity.prototype.init.prototype = wCity.prototype;
    window.wCity = wCity();

    window.wIsWeixin=function(){
        var ua = window.navigator.userAgent.toLowerCase();
        return ua.match(/MicroMessenger/i) == 'micromessenger';
    };
    window.wIsAlipay = function() {
        var ua = window.navigator.userAgent.toLowerCase();
        return ua.match(/AlipayClient/i) == 'alipayclient';
    };
    window.wIsUnionPay = function() {
        var ua = window.navigator.userAgent.toLowerCase();
        return ua.match(/UnionPay/i) == 'unionpay';
    };
})(window);


